package com.example.service;

import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 审批任务服务类
 * 用于创建或签审批任务
 */
@Component
public class ApprovalTaskService implements JavaDelegate {
    
    @Autowired
    private TaskService taskService;
    
    @Override
    public void execute(DelegateExecution execution) {
        // 获取审批组
        @SuppressWarnings("unchecked")
        Set<String> approverGroups = (Set<String>) execution.getVariable("approverGroups");
        
        if (approverGroups != null && !approverGroups.isEmpty()) {
            // 记录审批组数量，用于后续判断是否所有任务都已完成
            execution.setVariable("approverGroupCount", approverGroups.size());
            
            int taskIndex = 0;
            // 为每个组创建一个审批任务
            for (String group : approverGroups) {
                Task task = taskService.newTask();
                task.setName("审批任务 - " + group);
                task.setDescription("文档审批");
                task.setCategory("document-approval");
                task.setProcessInstanceId(execution.getProcessInstanceId());
                task.setExecutionId(execution.getId());
                taskService.saveTask(task);
                
                // 设置任务候选组
                taskService.addCandidateGroup(task.getId(), group);
                
                // 将任务ID存储到流程变量中
                execution.setVariable("approvalTask_" + taskIndex, task.getId());
                taskIndex++;
            }
        }
    }
}